package com.springcloud.alibaba.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class SentineFlowDemo {

    public static void main(String[] args) {

        initFlowRules();
        Executor executor = Executors.newFixedThreadPool(100);
        Date date = new Date();
        while(true) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    Entry entry = null;
                    try {
                        entry = SphU.entry("hello world");
                        date.setTime(System.currentTimeMillis());
                        System.out.println(date.toInstant());
                    } catch (BlockException e) {
//                        e.printStackTrace();
                    } catch (Exception e) {
                        Tracer.traceEntry(e, entry);
                    } finally {
                        if(entry != null) {
                            entry.exit();
                        }
                    }
                }
            });
        }

    }

    public static void initFlowRules() {
        List<FlowRule> flowRules = new ArrayList();
        FlowRule flowRule = new FlowRule();
        flowRule.setCount(20);
        flowRule.setResource("hello world");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRules.add(flowRule);
        FlowRuleManager.loadRules(flowRules);
    }

}
